﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Events;

public class Level : MonoBehaviour {

	public int levelID;//关卡ID
	public string levelName;//关卡名字
	public GameObject bossPrefab;//boss预制体
	public float bossTime;//boss出现时间
	public List<SpawnRule> ruleList=new List<SpawnRule>();//怪物生成规则
	public Level_Result result=Level_Result.None;//关卡结果
	
	float levelSinceStartTime=0;//关卡经过时间
	float startLevelTime=0;//关卡开始时间
	Boss boss=null;//boss脚本
    private Player player;//玩家脚本
	
	void Start () {
        player = FindObjectOfType<Player>();
		StartCoroutine (LevelStart ());
		startLevelTime = Time.time;
	}

    //关卡开始
	IEnumerator LevelStart()
	{
		string str = string.Format ("Level {0}   {1}", levelID, levelName);
		UIManager.Instance.UIlevel (str);
		yield return new WaitForSeconds (2f);
		for(int i=0;i<ruleList.Count;i++)
			Instantiate<SpawnRule> (ruleList [i]);
	}

	//boss生成规则
	void Update () {
		if (result == Level_Result.LevelSuccess)
			return;
		levelSinceStartTime = Time.time - startLevelTime;
		if (levelSinceStartTime > bossTime)
		{
			if(boss==null)
			{
				boss=(Boss)UnitManager.Instance.CreateEnemy(bossPrefab);
				boss.target=player;
                event_manager.Instance.add_listener("BossDie", BossDie);	
			}
		}
	}

    //boss死亡触发
	private void BossDie(object udata)
	{
		result = Level_Result.LevelSuccess;
        event_manager.Instance.dispatch_event("LevelUp", null);
	}
}
